<template>
  <div class="bg-white p-20px -mt-5px">
    <!-- 表格 -->
    <el-table
      :data="currentPageData"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      @cell-dblclick="handleCellDbClick"   
      @row-dblclick="handleRowDbClick"
      @row-click="handleRowClick"
      @cell-click="handleCellClick"      
      :row-class-name="props.rowClassName ?? tableRowClassName"
    >
      <!-- 选择列 -->
      <el-table-column
        v-if="showSelection"
        type="selection"
        width="55"
        align="center"
      ></el-table-column>

      <!-- 序号列 -->
      <el-table-column
        type="index"
        label="序号"
        width="50"
        align="center"
      ></el-table-column>

      <!-- 动态列 -->
      <el-table-column
        v-for="column in visibleColumns"
        :key="column.field"
        :prop="column.field"
        :label="column.label"
        :width="column.width"
        :align="column.align || 'left'"
        :sortable="column.sortable ? 'custom' : false"
        :filters="column.filters"
        :filter-method="column.filters ? filterHandler : null"
      ></el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="pageSizes"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px"
    ></el-pagination>
  </div>
</template>

<script setup>
// import { ref, computed, defineProps, defineEmits, watch } from 'vue';
import { ref, computed,   watch } from 'vue';
import defaultConfig from '@config/index.js'; // 相对路径

const props = defineProps({
  tableColumns: {
    type: Array,
    required: true,
    default: () => [],
  },
  tableData: {
    type: Array,
    required: true,
    default: () => [],
  },
  pageSize: {
    type: Number,
    default: defaultConfig.tablePageSize,// 10
  },
  pageSizes: {
    type: Array,
    default: () => defaultConfig.tablePageSizes//[5, 10, 15, 20],
  },
  showSelection: {
    type: Boolean,
    default: false,
  },
   rowClassName: {
    type: Function,
    default: null       // 不传就用内部默认的
  },
});

const emit = defineEmits(['update:currentPage', 
                          'update:pageSize', 
                          'selection-change',
                          'cell-dblclick',
                          'row-dblclick',
                          'cell-click',   
                          'row-click'     ]);


const currentPage = ref(defaultConfig.tableCurrentPage);
const sortedTableData = ref([...props.tableData]);
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * props.pageSize;
  const end = start + props.pageSize;
 return sortedTableData.value.slice(start, end);
  //  return props.tableData.slice(start, end);
});

const visibleColumns = computed(() => {
  return props.tableColumns.filter((column) => !column.hide).map(column => {
    // 自动筛选功能
    if (column.is_filter) {
      // 提取该列所有唯一值作为筛选项，并按升序排序
      const uniqueValues = [...new Set(props.tableData.map(item => item[column.field]))]
        .sort((a, b) => {
          // 如果是数字类型，按数值排序
          if (typeof a === 'number' && typeof b === 'number') {
            return a - b;
          }
          // 如果是字符串类型，按字典序排序
          return String(a).localeCompare(String(b));
        });
      
      const filters = uniqueValues.map(value => ({
        text: String(value),
        value: value
      }));
      return {
        ...column,
        filters
      };
    }
    return column;
  });
});

const filterHandler = (value, row, column) => {
  const property = column['property'];
  return row[property] === value;
};

// 在 script setup 中添加
const handleSortChange = (sortInfo) => {
  const { prop, order } = sortInfo;
  let sortedData = [...props.tableData];
  
  if (order === 'ascending') {
    sortedData = [...props.tableData].sort((a, b) => {
      if (typeof a[prop] === 'number' && typeof b[prop] === 'number') {
        return a[prop] - b[prop];
      }
      return String(a[prop]).localeCompare(String(b[prop]));
    });
  } else if (order === 'descending') {
    sortedData = [...props.tableData].sort((a, b) => {
      if (typeof a[prop] === 'number' && typeof b[prop] === 'number') {
        return b[prop] - a[prop];
      }
      return String(b[prop]).localeCompare(String(a[prop]));
    });
  }
  
  // 更新排序后的数据
  sortedTableData.value = sortedData;
};
const handleSizeChange = (newSize) => {
  console.log(`分页大小改变，新的分页大小为: ${newSize}`);
  emit('update:pageSize', newSize);
  currentPage.value = 1; // 重置当前页为第一页
  emit('update:currentPage', currentPage.value);
  sortedTableData.value = [...props.tableData];
};

const handleCurrentChange = (newPage) => {
  console.log(`当前页码改变，新的页码为: ${newPage}`);
  currentPage.value = newPage;
  emit('update:currentPage', currentPage.value);
};

const handleSelectionChange = (selection) => {
  emit('selection-change', selection);
};

const handleCellDbClick = (row, column, cell, event) => {
  emit('cell-dblclick', row, column, cell, event);   // ← 小写 c + 直接传参数
}

const handleRowDbClick = (row, event) => {
  emit('row-dblclick', row, event);                  // ← 小写 r + 直接传参数
}
const handleCellClick = (row, column, cell, event) => {
  emit('cell-click', row, column, cell, event);   // ← 小写 c + 直接传参数
}

const handleRowClick = (row, event) => {
  emit('row-click', row, event);                  // ← 小写 r + 直接传参数
}

function tableRowClassName({ rowIndex }) {
 return rowIndex % 2 === 0 ? 'row-gray-50' : 'row-white'; // 偶行极浅灰，奇行保持白底
}
// 监听 currentPage 和 pageSize 的变化并记录日志
watch(currentPage, (newVal, oldVal) => {
  console.log(`currentPage changed from ${oldVal} to ${newVal}`);
});

watch(() => props.pageSize, (newVal, oldVal) => {
  console.log(`pageSize changed from ${oldVal} to ${newVal}`);
});
// 监听 tableData 变化并同步更新 sortedTableData
watch(() => props.tableData, (newData) => {
  sortedTableData.value = [...newData];
}, { immediate: true });
</script>
